package ccnt.pvc.scudwaremobile.utils;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import android.os.Bundle;
import ccnt.pvc.scudwaremobile.dao.ApkModel;
import ccnt.pvc.scudwaremobile.dao.ServiceModel;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;

import edu.mit.media.funf.Utils;

public class JsonUtils {

	public static Gson getGson() {
		return new GsonBuilder().setPrettyPrinting().registerTypeAdapter(Bundle.class, new BundleJsonSerializer()).create();
	}

	public static class BundleJsonSerializer implements JsonSerializer<Bundle> {
		@Override
		public JsonElement serialize(Bundle bundle, Type type, JsonSerializationContext context) {
			JsonObject object = new JsonObject();
			for (Map.Entry<String, Object> entry : Utils.getValues(bundle).entrySet()) {
				object.add(entry.getKey(), context.serialize(entry.getValue()));
			}
			return object;
		}
	}
	
	public static List<ApkModel> convertToApks(String json) {
		
		List<ApkModel> apks = new ArrayList<ApkModel>();

		JsonArray jsonArray = (JsonArray) new JsonParser().parse(json);

		for (int i = 0; i < jsonArray.size(); i++) {
			JsonObject ele = (JsonObject) jsonArray.get(i);
			ApkModel apk = new ApkModel();
			apk.setApkName(ele.get("apkName").getAsString());
			apk.setPackageName(ele.get("packageName").getAsString());
			apk.setVersion(ele.get("version").getAsString());
			apk.setDeveloper(ele.get("developer").getAsString());
			apks.add(apk);
		}

		return apks;
	}
	
	public static List<ServiceModel> convertToServices(String json) {
		
		List<ServiceModel> services = new ArrayList<ServiceModel>();
		JsonArray jsonArray = (JsonArray) new JsonParser().parse(json);
		for(int i=0; i<jsonArray.size(); i++) {
			JsonObject ele = (JsonObject) jsonArray.get(i);
			ServiceModel service = new ServiceModel();
			service.setClassName(ele.get("className").getAsString());
			service.setPackageName(ele.get("packageName").getAsString());
			service.setDeviceName(ele.get("deviceName").getAsString());
			service.setCategory(ele.get("category").getAsInt());
			service.setSensorName(ele.get("sensorName").getAsString());
			service.setDataType(ele.get("dataType").getAsString());
			service.setMeasure(ele.get("measure").getAsString());
			service.setLevel(ele.get("level").getAsInt());
			service.setParams(ele.get("params").getAsString());
			service.setDescription(ele.get("description").getAsString());
			services.add(service);
		}
		return services;
	}
}
